package com.fastloan.utils;

import okhttp3.*;

import java.io.IOException;
import java.util.Map;

/**
 * @author rankai
 *         createTime 2017-08-2017/8/16 17:25
 */
public class HttpUtil {

    public static String get(String url) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).get().build();
        try {
            Response response = client.newCall(request).execute();
            return value(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String post(String url, String json) {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        try {
            Response response = client.newCall(request).execute();
            return value(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Response postByte(String url, String json) {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        try {
            return client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String post(String url, Map<String, Object> map) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).post(buildBody(map)).build();
        try {
            Response response = client.newCall(request).execute();
            return value(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static RequestBody buildBody(Map<String, Object> map) {
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            builder.add(entry.getKey(), entry.getValue().toString());
        }
        return builder.build();
    }

    private static String value(Response response) throws IOException {
        if (response != null && response.isSuccessful()) {
            String value = response.body().string();
            return value;
        }
        return null;
    }
}
